"""
将产品采集到店小秘
"""
from time import sleep, time

from playwright.async_api import async_playwright

from utils.product_collector import ProductCollector


def get_products(classify, num):
    validate_products = []

    pc = ProductCollector()

    page = 0
    size = num

    while True:
        page += 1

        # 获取产品
        products = pc.get_product_record(classify=classify, is_collection=False, page=page, num=size)
        if not products:
            break
        for product in products:
            code = product[1]
            star = product[5]
            comment_num = product[6]
            ship_from = product[7]
            is_chinese_seller = True if product[8] == 1 else False

            # 检查评分
            if not star or float(star) <3.8:
                continue
            # 检查评论数
            if not comment_num or comment_num < 50:
                continue
            # 检查是否亚马逊派送
            if not ship_from or "Amazon" not in ship_from:
                continue
            # 检查是否中国商家
            if not is_chinese_seller:
                continue

            validate_products.append(code)

            # 达到目标数量
            if len(validate_products) == num:
                break

        # 达到目标数量
        if len(validate_products) == num:
            break

    return validate_products


async def collect_product(p, code):
    browser = await p.chromium.connect_over_cdp('http://localhost:9223')
    browser = browser.contexts[0]
    await browser.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())

    start_time = time()

    # 打开页面，最多尝试10次
    product_page = None
    for _ in range(10):
        product_page = await browser.new_page()
        try:
            await product_page.goto(f'https://www.amazon.com/dp/{code}', timeout=100000, wait_until='domcontentloaded')
            while True:
                collect_btn = await product_page.query_selector('.dxmFetchBtn')
                if collect_btn:
                    break
            break
        except Exception as _:
            await product_page.close()
    if not product_page:
        print(f'Failed to open product page: {code}')
        return

    # 点击采集按钮
    sleep(1)
    collect_btn = await product_page.query_selector('.dxmFetchBtn')
    if not collect_btn:
        await product_page.close()
        print(f'Failed to find collect button: {code}')
        return
    while True:
        collect_btn = await product_page.query_selector('.dxmFetchBtn')
        try:
            await collect_btn.click()
        except Exception as _:
            continue
        break
    sleep(1)

    # 等待采集结果
    is_collected = False
    start_collect_time = time()
    while True:
        if time() - start_collect_time > 5 * 60:
            print(f'Failed to collect product {code} in 5 minutes')
            break
        collect_btn_text = await collect_btn.inner_text()
        tip_element = await product_page.query_selector('.modal-alert-content')
        tip_text = None
        if tip_element:
            tip_text = await tip_element.inner_text()
        if tip_text and "已有采集记录" in tip_text:
            print(f'Product {code} has been collected')
            break
        if collect_btn_text == '采集成功':
            is_collected = True
            break

    pc = ProductCollector()
    pc.product_2_collection(code)

    all_elapsed_time = time() - start_time
    collect_time = time() - start_collect_time
    print(f'[{code}] 采集{"成功" if is_collected else "失败"}. 采集耗时: {collect_time:.2f}秒. 总耗时: {all_elapsed_time:.2f}秒.')
    await product_page.close()
    return is_collected



if __name__ == '__main__':
    import asyncio

    async def main():
        ps = get_products('1004', 98)
        for c in ps:
            p = await async_playwright().start()
            await collect_product(p, c)

    asyncio.run(main())


